<template>
  <div id="content">
    <el-container>
      <el-main>
        <el-card shadow="always" header="登录">
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
          >
            <el-form-item label="用户名" prop="userName">
              <el-input
                v-model="ruleForm.userName"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="pass">
              <el-input
                type="password"
                v-model="ruleForm.pass"
                autocomplete="off"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >登录</el-button
              >
              <el-button @click="register()">注册</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>

<script>
import store from '../store';

export default {
  name: "Login",
  data() {
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };
    return {
      ruleForm: {
        userName: '',
        pass: "",
      },
      rules: {
        pass: [{ validator: validatePass, trigger: "blur" }],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$apiFun.postLogin({
            name: this.ruleForm.userName,
            password: this.ruleForm.pass
          }).then(response => {
            if(response['success']) {
              console.log(response.data.token)
              this.$store.commit('setToken', response['data']['token'])
              if(this.ruleForm.userName == 'admin')
              this.$router.push('/admin')
              else
              this.$router.push('/home')
            } else {
              alert(response['msg'])
            }
          }).catch(err => {
            console.log(err)
          })
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    register() {
      this.$router.push('/register')
    },
  },
};
</script>

<style>
.grid-content {
  min-height: 36px;
}
.el-row {
  margin-bottom: 20px;
}
#content {
  width: 100%;
  min-height: 100vh;
  background: url("/static/login_bg.webp") center center no-repeat;
  background-size: 100% 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
